import com.hp.ifc.attachments.Attachment;
import com.hp.ifc.attachments.AttachmentServer;
import com.hp.ifc.rep.AppGeneralSettings;
import com.hp.ifc.rep.AppGeneralSettingsEnum;
import com.hp.ifc.types.AppOID;
import com.hp.itsm.api.ApiSDSession;
import com.hp.itsm.api.interfaces.IAttachedItem;
import com.hp.itsm.api.interfaces.IChangeHome;
import com.hp.itsm.api.interfaces.IConfigurationItemHome;
import com.hp.itsm.api.interfaces.IGeneralSettingsHome;
import com.hp.itsm.api.interfaces.IIncidentHome;
import com.hp.itsm.api.interfaces.ILifeCycleObject;
import com.hp.itsm.api.interfaces.IPersonHome;
import com.hp.itsm.api.interfaces.IProblemHome;
import com.hp.itsm.api.interfaces.IServicecallHome;
import com.hp.itsm.api.interfaces.IWorkorderHome;

/**
 * This example shows how an attachment can be retrieved from attachment server.
 * It opens a session using the server name, user name and the password.
 * Next it opens an item using the item type and the item id and it tries
 * to pull attachments to local folder.
 * Note: The sample needs <client install folder>\lib\libftp.jar package
 */

public class ApiPullAttachments {

	public static void main(String[] args) {
		if (args.length != 6) {
			System.err
					.println("Usage : "
							+ "PullAttachments <server> <username> <password> <item> <id> <localfolder>");
			System.err
					.println("<item>: "
							+ "ConfigurationItem, Incident, Servicecall, Problem, Change, Workorder");
			return;
		}

		String server = args[0];
		String username = args[1];
		String password = args[2];
		String itemType = args[3];
		long id = Long.valueOf(args[4]).longValue();
		String LocalFolder = args[5];

		/*
		 * Open a session to a running Service Desk application Server. Once you
		 * have a connection, you can use it to communicate with the server. The
		 * connection has an instance of the workflow layer on the server that
		 * keeps the state information of this client.
		 */
		ApiSDSession session = null;
		try {
			session = ApiSDSession.openSession(server, username, password);
		} catch (RuntimeException e) {
			/*
			 * Connecting can go wrong for various reasons. E.G. No server is
			 * running on this particular computer/port combination or the
			 * user/password combination is wrong. Catch the exception and print
			 * an error message for the user or for the log. The Web-API makes
			 * an effort to give sensible messages in the exceptions, and if
			 * possible, the messages are localised.
			 * 
			 * Note: in some applications System.out.println() does not work.
			 */
			System.out.println(e.getMessage());
			return;
		}

		// Decide on the item type and open the item with the passed id
		ILifeCycleObject item = null;
		try {
			if (itemType.equalsIgnoreCase("ConfigurationItem")) {
				IConfigurationItemHome ciHome = session
						.getConfigurationItemHome();
				item = ciHome.openConfigurationItem(id);
			} else if (itemType.equalsIgnoreCase("Incident")) {
				IIncidentHome incHome = session.getIncidentHome();
				item = incHome.openIncident(id);
			} else if (itemType.equalsIgnoreCase("Servicecall")) {
				IServicecallHome scHome = session.getServicecallHome();
				item = scHome.openServicecall(id);
			} else if (itemType.equalsIgnoreCase("Problem")) {
				IProblemHome pbHome = session.getProblemHome();
				item = pbHome.openProblem(id);
			} else if (itemType.equalsIgnoreCase("Change")) {
				IChangeHome chHome = session.getChangeHome();
				item = chHome.openChange(id);
			} else if (itemType.equalsIgnoreCase("Workorder")) {
				IWorkorderHome woHome = session.getWorkorderHome();
				item = woHome.openWorkorder(id);
			} else {
				System.out.println("Unknown item type: " + itemType);
				return;
			}
		} catch (RuntimeException e) {
			System.out.println("Exception for itemType = " + itemType
					+ " and id = " + id);
			System.out.println(e.getMessage());
			return;
		}
        
        //get attachment server information
        IGeneralSettingsHome gsh = session.getGeneralSettingsHome();
        final String attachmentServerName = (gsh.openGeneralSettings(new Long(AppGeneralSettingsEnum.stAttachmentServerName))).getValue();
        final String attachmentServerUserName = (gsh.openGeneralSettings(new Long(AppGeneralSettingsEnum.stAttachmentServerUsername))).getValue();
        final String attachmentServerPassword = (gsh.openGeneralSettings(new Long(AppGeneralSettingsEnum.stAttachmentServerPassword))).getValue();
        final String attachmentServerTargetFolder = (gsh.openGeneralSettings(new Long(AppGeneralSettingsEnum.stAttachmentServerTargetFolder))).getValue();
        final String usePassiveFTP = (gsh.openGeneralSettings(new Long(AppGeneralSettingsEnum.stAttachmentServerUsePassiveFTP))).getValue();

		if ((attachmentServerName == null)
				|| (attachmentServerName.length() == 0)
				|| (attachmentServerUserName == null)
				|| (attachmentServerUserName.length() == 0)
				|| (attachmentServerPassword == null)
				|| (attachmentServerPassword.length() == 0)
				|| (attachmentServerTargetFolder == null)
				|| (attachmentServerTargetFolder.length() == 0)) {
			System.out.println("information isn't enough: ");
			return;
		}
		
		final int server_type = AttachmentServer.ATS_FTP_SERVER;

		final AttachmentServer attachmentServer = AttachmentServer.openAttachmentServer(
				server_type, new String[]{attachmentServerName,
						attachmentServerTargetFolder, attachmentServerUserName,
						attachmentServerPassword,
						usePassiveFTP});

		try {
			Boolean flag = (item.getAttachment()).getAttachmentExists();
			if (flag.booleanValue() == true) {
				IAttachedItem[] atts = (item.getAttachment())
						.getAttachedItems();
				for (int i = 0; i < atts.length; i++) {
					IAttachedItem attachedItem = atts[i];
					Attachment attachmentsHandle = attachmentServer
							.openAttachment(itemType, new AppOID(item.getOID()
									.longValue()));
					com.hp.ifc.attachments.AttachedItem att = attachmentsHandle
							.openAttachedItem(new AppOID(attachedItem.getOID()
									.longValue()));
                    
                    System.out.println(LocalFolder + System.getProperty("file.separator") + attachedItem.getBaseName());
                    att.getCopy(LocalFolder + System.getProperty("file.separator") + attachedItem.getBaseName());
				}
			}
		} catch (Throwable t) {
			t.printStackTrace();
		} finally {
			if (attachmentServer != null) {
				attachmentServer.close();
			}
		}

	}

}